<template>
  <div class="chat-msg-item">
    <div class="chat-msg-tip" v-show="msgInfo.type==10">{{ msgInfo.content }}</div>
    <div class="chat-msg-normal" v-show="msgInfo.type!=10" :class="{'chat-msg-mine':mine}">
      <div class="head-image">
        <head-image :url="headImage?store.state.imgUrl+headImage:logo"
        ></head-image>
      </div>
      <div class="chat-msg-content">
        <div class="chat-msg-top">
          <span>{{ showName }}</span>
          <chat-time :time="msgInfo.sendTime"></chat-time>
        </div>
        <div class="chat-msg-bottom">
          <div class="chat-msg-text" ref="chatMsgText" v-if="msgInfo.type==0"
               v-html="highlightKeyword(msgInfo.content)"></div>
          <div class="chat-msg-image" v-if="msgInfo.type==1">
            <div class="img-load-box" v-loading="loading"
                 element-loading-text="上传中.."
                 element-loading-background="rgba(0, 0, 0, 0.4)">
              <img class="send-image" :src="store.state.imgUrl+JSON.parse(msgInfo.content).originUrl"
                   @click="showFullImageBox()"/>
            </div>
            <span title="发送失败" v-show="loadFail" @click="handleSendFail"
                  class="send-fail el-icon-warning"></span>
          </div>
          <!--					<div class="chat-msg-file" v-if="msgInfo.type==2">-->
          <!--						<div class="chat-file-box" v-loading="loading">-->
          <!--							<div class="chat-file-info">-->
          <!--								<el-link class="chat-file-name" :underline="true" target="_blank" type="primary" :href="data.url">{{data.name}}</el-link>-->
          <!--								<div class="chat-file-size">{{fileSize}}</div>-->
          <!--							</div>-->
          <!--							<div class="chat-file-icon">-->
          <!--								<span type="primary" class="el-icon-document"></span>-->
          <!--							</div>-->
          <!--						</div>-->
          <!--						<span title="发送失败" v-show="loadFail" @click="handleSendFail" class="send-fail el-icon-warning"></span>-->
          <!--					</div>-->
          <div class="chat-msg-voice" v-if="msgInfo.type==3" @click="handlePlayVoice()">
            <audio controls :src="JSON.parse(msgInfo.content).url"></audio>
          </div>
          <div class="chat-msg-goods" v-if="msgInfo.type ==4" @click="gotoDetail(JSON.parse(msgInfo.content))">
            <div class="xfk" style="border-radius: 10px;padding: 11px;background: #ffffff;margin-bottom: 10px;">
              <div style="display: flex;justify-content: flex-start;align-items: center;">
                <img :src=" store.state.imgUrl + JSON.parse(msgInfo.content).goodPics.split(',')[0]"
                     style="width: 85px;height: 85px;"/>
                <div style="margin-left: 10px;text-align: left">
                  <div style="font-size: 14px;font-weight: 400;color: rgba(29, 22, 23, 1);">
                    {{ JSON.parse(msgInfo.content).name }}
                  </div>
                  <div style="display:flex;justify-content: space-around;align-items: center;margin-top: 10px;">
                    <div style="font-size: 18px;font-weight: 500;color: rgba(255, 0, 0, 1);">
                      ￥{{ JSON.parse(msgInfo.content).price }}
                    </div>
                    <div
                        style="font-size: 14px;font-weight: 400;color: rgba(199, 199, 199, 1);text-decoration: line-through;margin-left: 10px;">
                      ￥{{ JSON.parse(msgInfo.content).oldPrice }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import ChatTime from "../component/ChatTime.vue";
import HeadImage from "../component/HeadImage.vue";
import httpRequest from "@/api/httpRequest";
import store from '../../../store'
import axios from 'axios'
import {mapState} from "vuex";
import Cookies from "js-cookie";

export default {
  name: "messageItem",
  components: {
    ChatTime,
    HeadImage,
  },
  props: {
    mine: {
      type: Boolean,
      required: true
    },
    headImage: {
      type: String,
      required: false
    },
    showName: {
      type: String,
      required: true,
      default: ''
    },
    msgInfo: {
      type: Object,
      required: true,
    },
    menu: {
      type: Boolean,
      default: true
    },
    loading: {
      type: Boolean
    },
    loadFail: {
      type: Boolean
    }
  },
  data() {
    return {
      audioPlayState: 'STOP',
      store: store,
      logo: require("@/assets/tx.png"),
      isFlag: false
    }
  },
  methods: {
    // setVal(_val){
    //   let that=this
    //   console.log('zzz',_val)
    //   that.msgInfo = _val
    //   this.$nextTick(() => {
    //     this.$forceUpdate()
    //   })
    // },
    gotoDetail(item) {
      this.$store.state.isShopping = 0
      console.log('商品跳转到详情', item)
      this.$store.dispatch('shopping/setDetailId', item.id)
      this.$store.dispatch('shopping/setSkuId', item.skuId)
      this.$router.push({
        path: "/detail", query: {}
      });
    },
    // () {
    //   // this.$toast.fail('暂不支持该功能，请检查网络，再次发送')
    //   //先上传图片
    //   this.uploadImage()
    //
    // },
    // uploadImageUpdate(){
    //   this.$emit('update-image')
    // },
    handleSendFail() {
      let that = this
      let imageItem = this.failImageList.find((item, index) => item.uid == that.msgInfo.fileId)
      console.log('find item', JSON.stringify(imageItem))
      // let selectedFile = URL.createObjectURL(imageItem.raw);
      if (imageItem) {
        const formData = new FormData();
        formData.append("file", imageItem.raw)
        axios.post(`${store.state.baseUrlSecond}/image/upload`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data', // 设置请求头的 Content-Type
            'Authorization': 'Bearer ' + Cookies.get('token'), // 设置其他自定义请求头
          }
        }).then(response => {
          // 上传成功，获取返回的图片路径
          // this.imageUrl = response.data.imageUrl;
          that.msgInfo.content = JSON.stringify(response.data.data)
          console.log('上传完成之后拿到结果值后更新 msgInfo', that.msgInfo)
          httpRequest({
            url: this.messageAction,
            method: 'post',
            data: that.msgInfo
          }).then((id) => {
            that.msgInfo.loadStatus = 'ok';
            that.msgInfo.id = id;
            this.$store.commit("insertMessage", this.msgInfo);
            this.$forceUpdate()
          })


        })
            .catch(error => {
              // 处理上传失败的情况
              console.error(error);
            });
      } else {
        this.$toast.fail('没找到上传失败的图片')
      }
    }
    ,
    showFullImageBox() {
      let imageUrl = JSON.parse(this.msgInfo.content).originUrl;
      if (imageUrl) {
        this.$store.commit('showFullImageBox', imageUrl);
      }
    }
    ,
    handlePlayVoice() {
      console.log('开始播放')
      if (!this.audio) {
        this.audio = new Audio();
      }
      this.audio.src = JSON.parse(this.msgInfo.content).url;
      this.audio.play();
      this.handlePlayVoice = 'RUNNING';
    }
    ,
    handleSelectMenu(item) {
      this.$emit(item.key.toLowerCase(), this.msgInfo);
    }
    ,
    highlightKeyword(message) {
      if (this.keyword) {
        const regex = new RegExp(this.keyword, 'gi');
        return message.replace(regex, '<span style="background: blue;color: #ffffff">$&</span>');
      } else {
        return message;
      }
    }
    ,
  },
  computed: {
    ...mapState(['failImageList']),
    chatStore() {
      return this.$store.state.chatStore
    },
    keyword() {
      return this.$store.state.chatStore.searchKey
    },
    // eslint-disable-next-line vue/return-in-computed-property
    activeChat() {
      let index = this.chatStore.activeIndex;
      let chats = this.chatStore.chats
      if (index >= 0 && chats.length > 0) {
        console.log('sss', chats[index])
        return chats[index];
      }
      // // 当没有激活任何会话时，创建一个空会话，不然控制台会有很多报错
      // let emptyChat = {
      //   targetId: -1,
      //   showName: "",
      //   headImage: "",
      //   messages: []
      // }
      // console.log('改没改变', chats[index])
      // return emptyChat;
    },
    messageAction() {
      return `/message/${this.activeChat.type.toLowerCase()}/send`;
    },
    imageAction1() {
      // return `${process.env.VUE_APP_BASE_API}/image/upload`;
      return `${this.$store.state.baseUrlSecond}/image/upload1`;
      // return 'https://wechat.yasee.com.cn:8888/image/upload';
    },
    // data() {
    //   return JSON.parse(this.msgInfo.content)
    // },
    fileSize() {
      let size = this.data.size;
      if (size > 1024 * 1024) {
        return Math.round(size / 1024 / 1024) + "M";
      }
      if (size > 1024) {
        return Math.round(size / 1024) + "KB";
      }
      return size + "B";
    },
  },
  // watch: {
  // 'msgInfo': {
  //   handle(val) {
  //     console.log('qqq监听到loading变化',)
  //     this.$nextTick(() => {
  //       return val && val === "loading"
  //       // this.$forceUpdate();
  //     })
  //   },
  //   immediate: true
  // }
  // },
  mounted() {
    console.log('heagImage', this.headImage)
  },
}
</script>
<style lang="less" scoped>
.chat-msg-item {

  .chat-msg-tip {
    line-height: 50px;
  }

  .chat-msg-normal {
    position: relative;
    font-size: 0;
    margin-bottom: 10px;
    padding-left: 60px;
    min-height: 68px;

    .head-image {
      position: absolute;
      width: 40px;
      height: 40px;
      top: 0;
      left: 0;
    }

    .chat-msg-content {
      display: flex;
      flex-direction: column;

      .chat-msg-top {
        display: flex;
        flex-wrap: nowrap;
        color: #333;
        font-size: 14px;
        line-height: 20px;

        span {
          margin-right: 12px;
        }
      }

      .chat-msg-bottom {
        text-align: left;

        .chat-msg-text {
          position: relative;
          line-height: 22px;
          margin-top: 10px;
          padding: 10px;
          background-color: #ffffff;
          border-radius: 3px;
          color: #333;
          flex-direction: row-reverse;
          display: inline-block;
          font-size: 14px;
          word-break: break-word;

          .highlighted {
            background-color: red;
          }

          &:after {
            content: "";
            position: absolute;
            left: -10px;
            top: 13px;
            width: 0;
            height: 0;
            border-style: solid dashed dashed;
            border-color: #ffffff transparent transparent;
            overflow: hidden;
            border-width: 10px;
          }
        }

        .chat-msg-image {
          display: flex;
          flex-wrap: nowrap;
          flex-direction: row;
          align-items: center;

          .send-image {
            min-width: 50px;
            min-height: 50px;
            max-width: 60px;
            max-height: 60px;
            border: #dddddd solid 1px;
            cursor: pointer;
          }

          .send-fail {
            color: #e60c0c;
            font-size: 30px;
            cursor: pointer;
            margin: 0 20px;
          }
        }

        .chat-msg-file {
          display: flex;
          flex-wrap: nowrap;
          flex-direction: row;
          align-items: center;
          cursor: pointer;

          .chat-file-box {
            display: flex;
            flex-wrap: nowrap;
            align-items: center;
            width: 20%;
            min-height: 80px;
            border: #dddddd solid 1px;
            border-radius: 3px;
            background-color: #eeeeee;
            padding: 10px 15px;

            .chat-file-info {
              flex: 1;
              height: 100%;
              text-align: left;
              font-size: 14px;

              .chat-file-name {
                font-size: 16px;
                font-weight: 600;
                margin-bottom: 15px;
              }
            }

            .chat-file-icon {
              font-size: 50px;
              color: #d42e07;
            }
          }

          .send-fail {
            color: #e60c0c;
            font-size: 30px;
            cursor: pointer;
            margin: 0 20px;
          }
        }

        .chat-msg-voice {
          font-size: 14px;
          cursor: pointer;
          //border-radius: 3px;

          audio {
            width: 260px;
            height: 30px;
            padding: 5px;
            background: #ffffff;
          }
        }
      }
    }


    &.chat-msg-mine {
      text-align: right;
      padding-left: 0;
      padding-right: 60px;

      .head-image {
        left: auto;
        right: 5px;
      }

      .chat-msg-content {

        .chat-msg-top {
          flex-direction: row-reverse;

          span {
            margin-left: 12px;
            margin-right: 0;
          }
        }

        .chat-msg-bottom {
          text-align: right;

          .chat-msg-text {
            margin-left: 10px;
            background-color: rgba(242, 150, 0, 1);
            color: #fff;
            display: inline-block;
            vertical-align: top;
            font-size: 14px;

            .highlighted {
              background-color: yellow;
            }

            &:after {
              left: auto;
              right: -10px;
              border-top-color: rgba(242, 150, 0, 1);
            }
          }

          .chat-msg-image {
            flex-direction: row-reverse;
          }

          .chat-msg-file {
            flex-direction: row-reverse;
          }
        }
      }
    }
  }
}
</style>
